import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:im_app/im/util/DbUtil.dart';
import 'package:intl/intl.dart';

import '../../pojo/Enums.dart';
import '../../pojo/UiPojo.dart';
import '../../service/ContentSearchService.dart';
import '../../util/ImSingleton.dart';

final class ContentSearchCubit extends Cubit<ContentSearchState> {
  ContentSearchCubit() : super(ContentSearchState.init());

  void init() {
    emit(ContentSearchState.success([], [], []));
  }

  Future<void> search(String search) async {
    print("HotMessageCubit load!!");
    String userId = ImSingleton.getInstance().session.userId!;
    var contentSearchService = ContentSearchService();
    List<SearchResult> userSearchResults = await contentSearchService.searchUsers(search);
    List<SearchResult> groupSearchResults = await contentSearchService.searchGroups(userId, search);
    List<SearchResult> messageSearchResults = await contentSearchService.searchMessages(userId, search);
    emit(ContentSearchState.success(userSearchResults, groupSearchResults, messageSearchResults));
  }
}

final class ContentSearchState extends Equatable {

  final LoadingState state;
  final List<SearchResult> userSearchResults;
  final List<SearchResult> groupSearchResults;
  final List<SearchResult> messageSearchResults;

  const ContentSearchState._({
    this.state = LoadingState.loading,
    this.userSearchResults = const <SearchResult>[],
    this.groupSearchResults = const <SearchResult>[],
    this.messageSearchResults = const <SearchResult>[],
  });

  const ContentSearchState.loading() : this._();

  const ContentSearchState.init() : this._(state: LoadingState.success);

  const ContentSearchState.success(List<SearchResult> userSearchResults, List<SearchResult> groupSearchResults, List<SearchResult> messageSearchResults)
      : this._(state: LoadingState.success,
        userSearchResults: userSearchResults,
        groupSearchResults: groupSearchResults,
        messageSearchResults: messageSearchResults
      );

  const ContentSearchState.failure() : this._(state: LoadingState.failure);

  @override
  List<Object?> get props => [state, userSearchResults, groupSearchResults, messageSearchResults];

}